//
//  KLMDeviceNameControllerPopViewController.swift
//  KLM
//
//  Created by 朱雨 on 2023/8/25.
//

import UIKit
import nRFMeshProvision

class KLMDeviceNameControllerPopViewController: UIViewController {
    
    enum DevicesubType {
        case RGBSubType ///RGB负载
        case allInOneType ///多合一类型
    }
    
    typealias TypeBlock = (_ type: Int) -> Void
    typealias NameBlock = (_ name: String) -> Void
    
    @IBOutlet weak var contentView: UIView!
    @IBOutlet weak var loadTypeLab: UILabel!
    @IBOutlet weak var textField: CMTextField!
    @IBOutlet weak var loadTypeView: UIView!
    
    @IBOutlet weak var loadTypeBgView: UIView!
    
    @IBOutlet weak var titleLab: UILabel!
    
    @IBOutlet weak var loadTypeTipLab: UILabel!
    
    @IBOutlet weak var cancelBtn: UIButton!
    @IBOutlet weak var confirmBtn: UIButton!
        
    //设备名称
    var name: String?
        
    var nameBlock: NameBlock?
    var typeBlock: TypeBlock?
    
    var cancelBlock: (() -> Void)?
    var allTypes: [KLMType] = [KLMType]()
    
    var devicesubType: DevicesubType = .RGBSubType

    //选择的负载
    var selectloadType: KLMType?
        
    override func viewDidLoad() {
        super.viewDidLoad()
        
        textField.limitTextLeght = 32

        let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: textField.height))
        textField.leftView  = leftView
        textField.leftViewMode = .always
        textField.layer.cornerRadius = 4
        
        contentView.layer.cornerRadius = 8
        
        var str: String = Bundle.main.path(forResource: "RGBLoadTypePlist", ofType: "plist")!
        if devicesubType == .allInOneType {
//            str = Bundle.main.path(forResource: "RKAllInOneType", ofType: "plist")!
            str = Bundle.main.path(forResource: "RKAllInOneTypeTest", ofType: "plist")!
        }
        let loadTypes: NSArray = try! NSArray.init(contentsOf: URL.init(fileURLWithPath: str), error: ())
        allTypes = KLMTool.jsonToModel(type: KLMType.self, array: loadTypes as! [[String : Any]])!
        
        ///国际化
        titleLab.text = KLMLocalizable.LANGLOC("Name the device")
        textField.placeholder = KLMLocalizable.LANGLOC("Please enter a name")
        loadTypeTipLab.text = KLMLocalizable.LANGLOC("Select type")
        cancelBtn.setTitle(KLMLocalizable.LANGLOC("Cancel"), for: .normal)
        confirmBtn.setTitle(KLMLocalizable.LANGLOC("Confirm"), for: .normal)
        
        contentView.backgroundColor = appBackGroupColor
        loadTypeBgView.backgroundColor = appBackGroupColor
        
//        if apptype == .targetUnibright {
//            titleLab.textColor = AppTextColor
//            textField.placeHolderColor = AppPlaceHolderColor
//            textField.textColor = AppTextColor
//            textField.backgroundColor = unibrightViewBgColor
//            loadTypeTipLab.textColor = AppTextColor
//            loadTypeLab.textColor = AppTextColor
//            loadTypeView.backgroundColor = unibrightViewBgColor
//            cancelBtn.setTitleColor(AppTextColor, for: .normal)
//            confirmBtn.setTitleColor(AppTextColor, for: .normal)
//        }
        
        setupData()
    }
    
    private func setupData() {
                
        textField.text = name
        
    }
    
    @IBAction func sure(_ sender: Any) {

        guard let text = KLMTool.isEmptyString(string: textField.text) else {
            SVProgressHUD.showInfo(withStatus: textField.placeholder)
            return
        }
        
        ///检查是否重名
        if let network = MeshNetworkManager.instance.meshNetwork {
            
            let notConfiguredNodes = network.nodes.filter({ !$0.isConfigComplete && !$0.isProvisioner})
            if notConfiguredNodes.contains(where: {$0.name == text}) {
                SVProgressHUD.showInfo(withStatus: KLMLocalizable.LANGLOC("The name already exists"))
                return
            }
        }
        
        guard let cate = selectloadType  else {
            SVProgressHUD.showInfo(withStatus: KLMLocalizable.LANGLOC("Please select type"))
            return
        }
        if let typeB = typeBlock {
            typeB(cate.num)
        }
        
        if let nameB = nameBlock {
            nameB(text)
        }
        
        dismiss(animated: true, completion: nil)
    }
    
    @IBAction func tapCategory(_ sender: UITapGestureRecognizer) {
        
        let menuViewrect: CGRect = loadTypeView.convert(loadTypeView.bounds, to: KLMKeyWindow)
        let point: CGPoint = CGPoint.init(x: menuViewrect.origin.x, y: menuViewrect.origin.y + menuViewrect.size.height)
        var titles: [String] = [String]()
        for model in allTypes {
            titles.append(KLMLocalizable.LANGLOC(model.title))
        }
        YBPopupMenu.show(at: point, titles: titles, icons: nil, menuWidth: 180) { popupMenu in
            popupMenu?.priorityDirection = .none
            popupMenu?.arrowHeight = 0
            popupMenu?.minSpace = menuViewrect.origin.x
            popupMenu?.dismissOnSelected = true
            popupMenu?.isShadowShowing = false
            popupMenu?.delegate = self
            popupMenu?.cornerRadius = 0
            popupMenu?.maxVisibleCount = 6
        }
    }
        
    @IBAction func cancel(_ sender: Any) {
        if let cancel = cancelBlock {
            cancel()
        }
        
        dismiss(animated: true, completion: nil)
    }

}

extension KLMDeviceNameControllerPopViewController: YBPopupMenuDelegate {
    
    func ybPopupMenu(_ ybPopupMenu: YBPopupMenu!, didSelectedAt index: Int) {
        
        selectloadType = allTypes[index]
        loadTypeLab.text = KLMLocalizable.LANGLOC(selectloadType!.title)
        KLMLog("select = \(selectloadType)")
    }
}
